package com.xoms.admin.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.xoms.admin.controller.res.bean.RPurchaseBean;
import com.xoms.admin.controller.res.bean.RPurchaseInfoBean;
import com.xoms.admin.model.AccountBean;
import com.xoms.admin.model.AuditBean;
import com.xoms.admin.model.PurchaseBean;
import com.xoms.admin.model.PurchaseDetailBean;
import com.xoms.admin.model.vo.BatchPurchaseBean;
import com.xoms.admin.persist.dao.ProAuditDao;
import com.xoms.admin.persist.dao.ProductDao;
import com.xoms.admin.persist.dao.PurchaseDao;
import com.xoms.admin.service.PurchaseService;
import com.xoms.admin.service.exception.ServiceException;
import com.xoms.admin.service.res.PageResult;
import com.xoms.util.AppTextUtil;
import com.xoms.util.ArithUtil;
import com.xoms.util.DateTimeUtil;
import com.xoms.util.NumUtil;
import com.xoms.util.StringUtil;

@Service
public class PurchaseServiceImpl implements PurchaseService {

	@Autowired
	PurchaseDao purchaseImpl;

	@Autowired
	ProductDao productImpl;
	
	@Autowired
	ProAuditDao proAuditImpl;
	
	@Override
	public PageResult<RPurchaseBean> getPurchases(AccountBean account, String key, int page, int pageSize, String startTime,
			String endTime, String storeId) {
		PageResult<RPurchaseBean> result = new PageResult<RPurchaseBean>();
		List<RPurchaseBean> resList = new ArrayList<RPurchaseBean>();
		int count = purchaseImpl.selectCount(key, storeId, startTime, endTime);
		if(count > 0) {
			//查询入库单列表
			List<PurchaseBean> lists = purchaseImpl.selectList(key, page, pageSize, storeId, startTime, endTime);
			if (lists != null) {
				RPurchaseBean rb = null;
				for (PurchaseBean pur : lists) {
					rb=new RPurchaseBean();
					rb=parse(pur);
					resList.add(rb);
				}
			}
		}
		result.setData(resList);
		result.setCount(count);
		return result;
	}
	
	/**
	 * 格式化数据
	 * @param pure
	 * @return
	 */
	private RPurchaseBean parse(PurchaseBean pure) {
		RPurchaseBean res = new RPurchaseBean();
		res.setPurchaseId(pure.getPid());
		res.setPurchaseNo(pure.getPurchaseNo());
		res.setStoreHouse(pure.getStoreHouse());
		res.setBatch(pure.getBatch());
		res.setProvider(pure.getProvider());
		res.setTotalCost(pure.getTotalCost());
		res.setRemark(pure.getRemark());
		res.setAccountId(pure.getAccountId());
		res.setProviderId(pure.getProviderId());
		res.setStoreHouseId(pure.getStoreHouseId());
		res.setCreateTime(DateTimeUtil.formatTimestamp(pure.getCreateTime()));
		res.setAccount(pure.getAccount());
		res.setStatus(pure.getStatus());
		return res;
	}
 	

	@Override
	public PageResult<RPurchaseInfoBean> getPurchaseDetails(AccountBean account, String key, int page, int pageSize,
			String purchaseId, int paging) {
		PageResult<RPurchaseInfoBean> result = new PageResult<RPurchaseInfoBean>();
		List<RPurchaseInfoBean> resList = new ArrayList<RPurchaseInfoBean>();
		int count = purchaseImpl.selectDetailCount(key, purchaseId);
		if(count > 0) {
			//查询采购单列表
			List<PurchaseDetailBean> lists = purchaseImpl.selectDetailList(key, page, pageSize, purchaseId, paging);
			if (lists != null) {
				RPurchaseInfoBean rb = null;
				for (PurchaseDetailBean pur : lists) {
					rb = new RPurchaseInfoBean();
					rb = parseDetail(pur);
					resList.add(rb);
				}
			}
		}
		result.setData(resList);
		result.setCount(count);
		return result;
	}
	
	/**
	 * 格式化详情信息
	 * @param pur
	 * @return
	 */
	private RPurchaseInfoBean parseDetail(PurchaseDetailBean pur) {
		RPurchaseInfoBean result = new RPurchaseInfoBean();
		result.setPureNumber(pur.getNumber());
		result.setProduct(pur.getProduct());
		result.setProductId(pur.getProductId());
		result.setCategory(pur.getCategory());
		result.setPrice(pur.getPrice());
		result.setPurchaseId(pur.getPurchaseId());
		result.setStaleTime(pur.getStaleTime());
		result.setProductBar(pur.getProductBar());
		result.setUnit(pur.getUnit());
		result.setTranPurNumber(pur.getTranPurNumber());
		result.setTranNumber(pur.getTranNumber());
		result.setTranUnitId(pur.getTranUnitId());
		result.setTranUnit(pur.getTranUnit());
		return result;
	}

	@Transactional(rollbackFor = Exception.class)// 事务
	@Override
	public RPurchaseBean edit(AccountBean account, String pid, String storeId, String batch, String remark,
			Double totalCost, String details, String providerId, int isSubmit) {
		boolean flag = false;
		PurchaseBean data = new PurchaseBean();
		data.setStoreHouseId(storeId);
		data.setBatch(batch);
		data.setProviderId(providerId);
		data.setTotalCost(totalCost);
		data.setRemark(remark);

		if (StringUtil.isEmpty(pid)) {// 新建
			pid = AppTextUtil.getPrimaryKey();// id
			data.setPid(pid);
			data.setAccountId(account.getAccid());
			
			data.setStatus(isSubmit);// 未提交审核

			// 采购编号：PUR + YYYYMMDDHHmm + 0000001;一年百万数据？
			String maxNo = purchaseImpl.selectMaxPureNoInYear();// 获取当年采购单最大数量
			int num = 0;
			if(!StringUtil.isEmpty(maxNo)) {
				num = NumUtil.toInt(maxNo.substring(maxNo.length() - 7, maxNo.length()), 0);
			}
			String purchaseNo = AppTextUtil.getRandomProNo("Pur", (num + 1), 7);
			data.setPurchaseNo(purchaseNo);

			flag = purchaseImpl.insert(data) > 0;
			if (!flag) {
				throw new ServiceException("database_insert_fail","采购订单");
			}
			if(isSubmit == 2) { // 直接提交审核
				flag = submitAudit(account, data.getPid(), 1);
			}
		} else {
			data.setPid(pid);
			flag = purchaseImpl.update(data) > 0;// 更新数据库
			if (!flag) {
				throw new ServiceException("database_update_fail","采购订单");
			}
		}
		// 将采购商品详情信息批量更新到数据库
		if(!StringUtil.isEmpty(details)) { 
			flag = replaceBatchDetail(pid, details);
		}
		PurchaseBean res = purchaseImpl.selectOneById(pid);
		return parse(res);
	
	}

	/**
	 * 将采购商品详情信息批量插入数据库
	 * @param pid
	 * @param details
	 * @return
	 */
	private boolean replaceBatchDetail(String pid, String details) {
		boolean flag = false;
		double totalCost = 0;
		
		// JSON转list
		List<BatchPurchaseBean> batch = JSON.parseArray(details, BatchPurchaseBean.class);
		for(BatchPurchaseBean pure : batch) {
			pure.setPurchaseId(pid);
			totalCost = ArithUtil.add(totalCost, ArithUtil.mul(pure.getNumber(), pure.getPrice()));
			
		}

		if(batch.size() > 0) {
			// 删除当前采购单下所有关联采购单详情
			// 判断数量
			int detailCount = purchaseImpl.selectDetailCountById(pid);
			if(detailCount > 0) {
				// 删除当前采购单下所有关联采购单详情
				flag = purchaseImpl.delDetails(pid) > 0;
				if (!flag) {
					throw new ServiceException("database_delete_fail", "入库单详情");
				}
			}
			flag = purchaseImpl.replaceBatchDetail(batch) > 0;
			if (!flag) {
				throw new ServiceException("database_insert_fail","采购订单详情");
			}
		}

		flag = purchaseImpl.updateTotalCost(pid, totalCost) > 0;// 更新数据库
		if (!flag) {
			throw new ServiceException("database_update_fail","采购总金额");
		}
		return flag;
	}


	@Transactional(rollbackFor = Exception.class)// 事务
	@Override
	public boolean del(AccountBean account, String purchaseId) {
		boolean flag = false;
		// 删除采购单前判断是否已提交，提交的采购单不能删除
		PurchaseBean purchase = purchaseImpl.selectOneById(purchaseId);
		if(purchase == null) {// 采购单不存在
			throw new ServiceException("object_is_not_exist","采购单");
		}
		int status = NumUtil.toInt(purchase.getStatus(), 1);
		if(status != 1) {
			throw new ServiceException("object_is_submit", "采购单");
		}
		
		flag = purchaseImpl.del(purchaseId) > 0;
		if (!flag) {
			throw new ServiceException("database_delete_fail", "入库单");
		}
		// 判断数量
		int detailCount = purchaseImpl.selectDetailCountById(purchaseId);
		if(detailCount > 0) {
			// 删除当前采购单下所有关联采购单详情
			flag = purchaseImpl.delDetails(purchaseId) > 0;
			if (!flag) {
				throw new ServiceException("database_delete_fail", "入库单详情");
			}
		}
		return flag;
	}

	@Transactional(rollbackFor = Exception.class)// 事务
	@Override
	public boolean submitPurchase(AccountBean account, String purchaseId) {
		boolean flag = false;
		// 提交采购单前判断是否是待提交状态，提交的采购单不能多次提交
		PurchaseBean purchase = purchaseImpl.selectOneById(purchaseId);
		if(purchase == null) {// 采购单不存在
			throw new ServiceException("object_is_not_exist","采购单");
		}
		int status = purchase.getStatus();
		if(status != 1 && status != 4) {
			throw new ServiceException("object_is_not_unsubmit", "采购单");
		}
		flag = purchaseImpl.updateSubmitStatus(purchaseId, 2) > 0;// 更新采购单状态,1提交待审核
		if (!flag) {// 更新状态失败
			throw new ServiceException("database_update_fail","采购审核状态");
		}
		flag = submitAudit(account, purchaseId, 1);
		return flag;
	}

	private boolean submitAudit(AccountBean account, String tagetId, int type) {
		boolean flag = false;
		AuditBean audit = new AuditBean();// 添加到审核表
		audit.setAid(AppTextUtil.getPrimaryKey());
		audit.setSubmitId(account.getAccid());
		audit.setType(type);// 审核类型：1采购2入库3盘库4损耗5充公6冲正7退货到供应商
		audit.setTargetId(tagetId);// 关联id
		// 审核编号：SH+ YYYYMMDDHHmm + 0000001;一年百万数据？
		String maxNo = proAuditImpl.selectMaxAuditNoInYear(type);// 获取当年审核单最大数量
		int num = 0;
		if(!StringUtil.isEmpty(maxNo)) {
			num = NumUtil.toInt(maxNo.substring(maxNo.length() - 7, maxNo.length()), 0);
		}
		String auditNo = AppTextUtil.getRandomProNo("SH", (num + 1), 7);
		audit.setAuditNo(auditNo);
		audit.setStatus(0);
		
		flag = proAuditImpl.insert(audit) > 0;
		if (!flag) {// 插入状态失败
			throw new ServiceException("database_insert_fail","采购审核提交");
		}
		return flag;
	}

}
